/*
 * Galaxium Messenger
 * Copyright (C) 2008 Paul Burton <paulburton89@gmail.com>
 * 
 * License: GNU General Public License (GPL)
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation; either version 2 of the License, or (at your option)
 * any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

using System;
using System.Text;
using System.Xml;

using Anculus.Core;

using Galaxium.Core;

namespace Galaxium.Protocol.Msn
{
	//NOT 312
	//<NOTIFICATION ver="2" id="2" siteid="0" siteurl="http://g.live.com/"><TO name="account@address.whatever" pid="0x0:0x0"/><MSG pri="1" id="2"><ACTION url="5sten_gb/1"/><SUBSCR url="5sten_gb/1"/><BODY lang="1033" icon="/5sten_gb/2"><TEXT>Swap photos and files with your friends.</TEXT></BODY></MSG></NOTIFICATION>
		
	[MsnCommand ("NOT")]
	[PayloadCommand]
	public class NOTCommand : AbstractMsnCommand
	{
		XmlElement _data;
		XmlElement _to;
		
		public override byte[] Payload
		{
			get { return (_data != null) ? Encoding.UTF8.GetBytes (_data.OuterXml) : new byte[0]; }
			set
			{
				try
				{
					if (value.Length == 0)
						return;
					
					XmlDocument xml = new XmlDocument ();
					xml.LoadXml (Encoding.UTF8.GetString (value));
					
					ThrowUtility.ThrowIfFalse ("Invalid data", xml.DocumentElement.Name == "NOTIFICATION");
				
					_data = xml.DocumentElement;
					
					_to = _data["TO"];
				}
				catch (Exception ex)
				{
					Log.Warn (ex, "Couldn't decode NOT command payload");
				}
			}
		}
		
		public IEntity To
		{
			get
			{
				string uid = _to.GetAttribute ("name");
				
				if (string.IsNullOrEmpty (uid))
					return null;
				
				return Session.FindEntity (uid);
			}
		}
		
		public string SiteURL
		{
			get { return _data.GetAttribute ("siteurl"); }
		}
		
		public NOTCommand (MsnSession session, byte[] data)
			: base (session, data)
		{
		}
	}
}
